//
//  SetSecurityCodeViewController.m
//  Yihubang
//
//  Created by hyu on 16/8/1.
//  Copyright © 2016年 jinghao. All rights reserved.
//

#import "SetSecurityCodeViewController.h"

@interface SetSecurityCodeViewController ()
//@property (nonatomic, strong, readwrite) RACSignal *validcorrectSignal;
@property (weak  , nonatomic) IBOutlet UILabel  * myPhonelabel;
@property (weak  , nonatomic) IBOutlet UITextField  * codeTextField;
@property (weak  , nonatomic) IBOutlet UIButton * getCodeButton;
@property (weak  , nonatomic) IBOutlet UILabel  * getCodeTitle;
@property (weak, nonatomic) IBOutlet UIView *codeInputView;
@property (weak, nonatomic) IBOutlet UILabel *code_label1;
@property (weak, nonatomic) IBOutlet UILabel *code_label2;
@property (weak, nonatomic) IBOutlet UILabel *code_label3;
@property (weak, nonatomic) IBOutlet UILabel *code_label4;
@property (strong, nonatomic)          NSString * codeStr;
@property (strong, nonatomic)          NSNumber * littleTime ;
@property (strong, nonatomic)          NSTimer  * codeTimer ;
@property (strong, nonatomic)          NSArray  * codeLabelArr;
@end

@implementation SetSecurityCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"验证码";
    [self getCode];
    self.codeTextField.maxLenght = 4;
    [self.codeTextField becomeFirstResponder];
    self.codeLabelArr =@[self.code_label1,self.code_label2,self.code_label3,self.code_label4];
    @weakify(self);
    [self.codeInputView setTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        [self.codeTextField becomeFirstResponder];
    }];
    self.myPhonelabel.text =self.userClient.userName;
    [self.getCodeButton addTarget:self action:@selector(getCode) forControlEvents:UIControlEventTouchUpInside];
    RAC(self.getCodeButton, enabled) = [RACObserve(self, littleTime) map:^id(NSString *text) {
        return @([text integerValue] == 0);
    }];
    RACSignal * validLoginSignal= [self.codeTextField.rac_textSignal
                                   filter:^BOOL(NSString *password) {
                                       return password.length == 4;
                                   }];
    [validLoginSignal
     subscribeNext:^(NSNumber * usernameIsValid) {
         @strongify(self);
         [self nextStep];
     }];
    [self.codeTextField.rac_textSignal subscribeNext:^(NSString * code){
        @strongify(self);
        [self checkcodeLabelText:[code length]];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)checkcodeLabelText:(NSInteger)strLength{
    if([self.codeTextField.text length] == 0){
        strLength=0;
    }
        int number = 0;
        for (UILabel * codeLabel in self.codeLabelArr) {
            if(strLength > number){
                codeLabel.text = [self.codeTextField.text substringWithRange:NSMakeRange(number, 1)];
            }else{
                codeLabel.text = @"";
            }
            number++;
        }
}

- (void)changeTimeAtTimedisplay{
    self.littleTime = [NSNumber numberWithInt:self.littleTime.intValue-1];
    if (self.littleTime.intValue==0) {
        self.getCodeTitle.text = @"发送验证码";
        [self stopTimer];
    }else{
        self.getCodeTitle.text = [NSString stringWithFormat:@"重发验证码%@s",self.littleTime];
    }
}
- (void)stopTimer{
    if (_codeTimer) {
        [_codeTimer invalidate];
    }
    _codeTimer = nil;
}
-(void)nextStep{
    [self.codeTextField resignFirstResponder];
    if([self.codeTextField.text isEqualToString:self.codeStr]){
        UIStoryboard *HelpStory = [UIStoryboard storyboardWithName:@"Mine" bundle:[NSBundle mainBundle]];
        BaseViewController * BaseViewController = [HelpStory instantiateViewControllerWithIdentifier:@"AlterSecurityCideViewController"];
        [self.navigationController pushViewController:BaseViewController animated:YES];
    }else{
        [self hiddenHUDWithString:@"输入的验证码有误！" error:YES];
    }
     self.codeTextField.text = @"";
}

-(void)getCode{
    @weakify(self)
    [self startTimer];
    [[[HttpManagerCenter sharedHttpManager] sendPhoneCode:self.userClient.userName resultClass:nil] subscribeNext:^(BaseModel *model) {
        @strongify(self);
        if (model.code==200) {
            self.codeStr = model.data[@"code"];
        }else{
            [self showRequestErrorMessage:model];
        }
        
    } error:^(NSError *error) {
        [self hiddenHUDWithString:@"发送失败,重新获取" error:NO];
    } completed:^{
        
    }];
}
- (IBAction)changePhoneAction:(id)sender{
    UIStoryboard *HelpStory = [UIStoryboard storyboardWithName:@"Mine" bundle:[NSBundle mainBundle]];
    BaseViewController * BaseViewController = [HelpStory instantiateViewControllerWithIdentifier:@"ChangePhoneViewController"];
    [self.navigationController pushViewController:BaseViewController animated:YES];
}
-(NSString *)codeStr{
    if(!_codeStr){
        _codeStr =[NSString string];
    }
    return _codeStr;
}
- (NSTimer*)startTimer{
    if (!_codeTimer) {
        self.littleTime = [NSNumber numberWithInt:100];
        _codeTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeTimeAtTimedisplay) userInfo:nil repeats:YES];
    }
    return _codeTimer;
}
-(void)dealloc{
    [self stopTimer];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
